<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传示例</title>
    <style>
        .upload-container {
            max-width: 600px;
            margin: 50px auto;
            padding: 20px;
            background-color: #f9f9f9;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .upload-title {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }
        
        .file-input-container {
            position: relative;
            margin-bottom: 20px;
        }
        
        .custom-file-input {
            display: none;
        }
        
        .file-input-label {
            display: block;
            padding: 12px 20px;
            background-color: #0078ff;
            color: white;
            text-align: center;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .file-input-label:hover {
            background-color: #0056b3;
        }
        
        .file-info {
            margin-top: 10px;
            padding: 10px;
            background-color: #fff;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            display: none;
        }
        
        .file-info.visible {
            display: block;
        }
        
        .progress-container {
            width: 100%;
            height: 8px;
            background-color: #e0e0e0;
            border-radius: 4px;
            margin-top: 10px;
            overflow: hidden;
            display: none;
        }
        
        .progress-container.visible {
            display: block;
        }
        
        .progress-bar {
            height: 100%;
            background-color: #0078ff;
            border-radius: 4px;
            width: 0%;
            transition: width 0.3s ease;
        }
        
        .upload-btn {
            width: 100%;
            padding: 12px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
            margin-top: 10px;
        }
        
        .upload-btn:hover {
            background-color: #218838;
        }
        
        .upload-btn:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        
        .message {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            display: none;
        }
        
        .message.success {
            display: block;
            background-color: #d4edda;
            color: #155724;
        }
        
        .message.error {
            display: block;
            background-color: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <div class="upload-container">
        <h2 class="upload-title">文件上传</h2>
        
        <div class="file-input-container">
            <label class="file-input-label" for="fileInput">选择文件</label>
            <input type="file" id="fileInput" class="custom-file-input" accept="*/*">
            
            <div class="file-info" id="fileInfo">
                <div id="fileName"></div>
                <div id="fileSize"></div>
                <div class="progress-container" id="progressContainer">
                    <div class="progress-bar" id="progressBar"></div>
                </div>
            </div>
        </div>
        
        <button class="upload-btn" id="uploadBtn" disabled>上传文件</button>
        
        <div class="message" id="message"></div>
    </div>

    <script>
        const fileInput = document.getElementById('fileInput');
        const fileInfo = document.getElementById('fileInfo');
        const fileName = document.getElementById('fileName');
        const fileSize = document.getElementById('fileSize');
        const progressContainer = document.getElementById('progressContainer');
        const progressBar = document.getElementById('progressBar');
        const uploadBtn = document.getElementById('uploadBtn');
        const message = document.getElementById('message');
        
        let selectedFile = null;
        
        // 文件选择处理
        fileInput.addEventListener('change', (e) => {
            selectedFile = e.target.files[0];
            
            if (selectedFile) {
                fileInfo.classList.add('visible');
                fileName.textContent = `文件名: ${selectedFile.name}`;
                fileSize.textContent = `文件大小: ${formatFileSize(selectedFile.size)}`;
                uploadBtn.disabled = false;
                resetMessage();
            } else {
                fileInfo.classList.remove('visible');
                uploadBtn.disabled = true;
            }
        });
        
        // 上传按钮点击处理
        uploadBtn.addEventListener('click', uploadFile);
        
        // 文件上传函数
        function uploadFile() {
            if (!selectedFile) return;
            
            const formData = new FormData();
            formData.append('file', selectedFile);
            formData.append('uploader', 'user123'); // 可以添加额外的表单数据
            
            progressContainer.classList.add('visible');
            uploadBtn.disabled = true;
            
            fetch('/api/upload', {
                method: 'POST',
                body: formData,
                // 注意：上传文件时不要设置Content-Type，浏览器会自动设置正确的类型和边界
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                showMessage('上传成功! 文件ID: ' + data.fileId, 'success');
                progressBar.style.width = '100%';
                // 重置表单
                fileInput.value = '';
                fileInfo.classList.remove('visible');
                selectedFile = null;
                setTimeout(() => {
                    progressContainer.classList.remove('visible');
                    progressBar.style.width = '0%';
                }, 1000);
            })
            .catch(error => {
                showMessage('上传失败: ' + error.message, 'error');
                uploadBtn.disabled = false;
            });
        }
        
        // 显示消息
        function showMessage(text, type) {
            message.textContent = text;
            message.className = `message ${type}`;
        }
        
        // 重置消息
        function resetMessage() {
            message.textContent = '';
            message.className = 'message';
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            else if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
            else return (bytes / 1048576).toFixed(1) + ' MB';
        }
        
        // 添加拖拽功能
        const dropArea = document.querySelector('.upload-container');
        
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            dropArea.addEventListener(eventName, highlight, false);
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, unhighlight, false);
        });
        
        function highlight() {
            dropArea.style.border = '2px dashed #0078ff';
            dropArea.style.backgroundColor = 'rgba(0, 120, 255, 0.05)';
        }
        
        function unhighlight() {
            dropArea.style.border = '';
            dropArea.style.backgroundColor = '';
        }
        
        dropArea.addEventListener('drop', handleDrop, false);
        
        function handleDrop(e) {
            const dt = e.dataTransfer;
            selectedFile = dt.files[0];
            
            if (selectedFile) {
                fileInfo.classList.add('visible');
                fileName.textContent = `文件名: ${selectedFile.name}`;
                fileSize.textContent = `文件大小: ${formatFileSize(selectedFile.size)}`;
                uploadBtn.disabled = false;
                resetMessage();
            }
        }
    </script>
</body>
</html>